package com.mmall.seckill.rabbitMQ;

import com.mmall.seckill.util.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * Created by megan on 2018/7/26.
 * 发送消息
 */
@Slf4j
@Service
public class MQSender {

    @Resource
    private AmqpTemplate amqpTemplate;

    /**
     * Direct 模式交换机 Exchange
     */
    public void send(Object message){
        String msg = JsonUtil.obj2String(message);
        log.info("Direct 模式交换机 Exchange 发送消息 --> {} ",msg);
        amqpTemplate.convertAndSend(MQConfig.QUEUE,msg);
    }

    /**
     * topic 模式
     * @param message
     */
    public void sendTopic(Object message){
        String msg = JsonUtil.obj2String(message);
        log.info("topic 模式 发送消息 --> {}",msg);
        // 发送topic.key1 消息
        amqpTemplate.convertAndSend(MQConfig.TOPIC_EXCHANGE,MQConfig.ROUTING_KEY1,msg);
        // 发送topic.key2 消息
        amqpTemplate.convertAndSend(MQConfig.TOPIC_EXCHANGE,MQConfig.ROUTING_KEY2,msg);
    }

    /**
     * Fanout 模式 交换机Exchange (广播模式)
     */
    public void sendFanout(Object message){
        String msg = JsonUtil.obj2String(message);
        log.info("Fanout 模式 交换机Exchange (广播模式) 发送消息 --> {}",msg);
        amqpTemplate.convertAndSend(MQConfig.FANOUT_EXCHANGE,"",msg);
    }

    /**
     * Header 模式 交换机 Exchange
     * 里面必须出现 key，value ,根据header发送消息
     */
    public void sendHeader(Object message){
        String msg = JsonUtil.obj2String(message);
        log.info("Header 模式 交换机 Exchange 发送消息 --> {}",msg);
        MessageProperties properties = new MessageProperties();
        // 记住 一定要对应上才会发消息。。。。
        properties.setHeader("header1","value1");
        properties.setHeader("header2","value2");
        Message obj = new Message(msg.getBytes(),properties);
        amqpTemplate.convertAndSend(MQConfig.HEADER_EXCHANGE,"",obj);
    }

    /**
     * 秒杀发送消息
     * @param message
     */
    public void sendMiaoshaMessage(Object message){
        String msg = JsonUtil.obj2String(message);
        log.info("秒杀异步下单消息 --->  {}", msg);
        amqpTemplate.convertAndSend(MQConfig.QUEUE,msg);
    }
}
